package com.andyou.modules.sys.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.andyou.common.config.Global;
import com.andyou.common.mapper.JsonMapper;
import com.andyou.common.persistence.Page;
import com.andyou.common.utils.DateUtils;
import com.andyou.common.utils.GridVO;
import com.andyou.common.utils.StringUtils;
import com.andyou.common.utils.excel.ExportExcel;
import com.andyou.common.web.BaseController;
import com.andyou.modules.sys.entity.Dict;
import com.andyou.modules.sys.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 字典Controller
 * @author lgx
 * @version 2014-05-16
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/dict")
public class DictController extends BaseController {

	@Autowired
	private DictService dictService;
	
	@ModelAttribute
	public Dict get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return dictService.get(id);
		}else{
			return new Dict();
		}
	}
	
//	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = {"list", ""})
	public String list(Dict dict, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<String> typeList = dictService.findTypeList();
		model.addAttribute("typeList", typeList);
        Page<Dict> page = dictService.findPage(new Page<Dict>(request, response), dict); 
        model.addAttribute("page", page);
		return "modules/sys/dictList";
	}

//	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = "form")
	public String form(Dict dict, Model model) {
		model.addAttribute("dict", dict);
		return "modules/sys/dictForm";
	}

//	@RequiresPermissions("sys:dict:edit")
	@RequestMapping(value = "save")//@Valid 
	public String save(Dict dict, Model model, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/dict/?repage&type="+dict.getType();
		}
		if (!beanValidator(model, dict)){
			return form(dict, model);
		}
		dictService.save(dict);
		
		renderStringByJbox(response, "提交成功");
		return null;
		//addMessage(redirectAttributes, "保存字典'" + dict.getLabel() + "'成功");
		//return "redirect:" + adminPath + "/sys/dict/?repage&type="+dict.getType();
	}
	
//	@RequiresPermissions("sys:dict:edit")
	@RequestMapping(value = "delete")
	public String delete(Dict dict, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/dict/list?repage";
		}
		dictService.delete(dict);
		addMessage(redirectAttributes, "删除字典成功");
		return "redirect:" + adminPath + "/sys/dict/list?repage";
	}
	
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String type, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Dict dict = new Dict();
		dict.setType(type);
		List<Dict> list = dictService.findList(dict);
		for (int i=0; i<list.size(); i++){
			Dict e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("name", StringUtils.replace(e.getLabel(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}
	
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Dict> listData(@RequestParam(required=false) String type) {
		Dict dict = new Dict();
		dict.setType(type);
		return dictService.findList(dict);
	}
	
	@ResponseBody
	@RequestMapping(value="lableData")
	public Map<String, String> getLableData(@RequestParam(required=false) String type, String value){
		Dict dict = new Dict();
		dict.setType(type);
		dict.setValue(value);
		Map<String, String> lableMap = new HashMap<String, String>();
		
		List<Dict> list = dictService.findList(dict);
		
		if (list != null) {
			for( Dict dict1 : list){
				lableMap.put(dict1.getValue(), dict1.getLabel());
			}
		}
		
		return lableMap;
	}
	
	/** 
	 * 导出数据字典信息
	 * @param dict
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return （参数是否可空/不可空）
	 * @author Feng Xuwang
	 * Date:2016年11月16日；
	 */
	@RequestMapping(value = "export")
	public String exportFile(Dict dict, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "数据字典信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Dict> page = new Page<Dict>(request, response, -1);
			page.setPageSize(500000);
			page.setOrderBy("type");
			page = dictService.findPage(page, dict);
			new ExportExcel("数据字典信息", Dict.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出数据失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sys/dictList";
	}

	/**
	 * 获取数据字典列表
	 * @param dict
	 * @param request
	 * @param response
	 * @param model
	 * @return （参数不可空）
	 * @author vikingbin
	 * Date:2016年12月30日；
	 */
	@ResponseBody
	@RequestMapping(value = { "dictListJson" })
	public String dictListJson(Dict dict, HttpServletRequest request,
			HttpServletResponse response, Model model) {
	
		Page<Dict> page = dictService.findPage(new Page<Dict>(request, response,true),
				dict);
		model.addAttribute("page", page);

		GridVO gridVO = new GridVO();
		gridVO.setRows(page.getList());
		gridVO.setTotal(page.getCount());
		
		return JsonMapper.getInstance().toJson(gridVO);
	}
	
	/**
	 * 调用删除的方法
	 * @param dict
	 * @param redirectAttributes
	 * @return （参数不可空）
	 * @author vikingbin
	 * Date:2016年12月30日；
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAjax")
	public String deleteAjax(Dict dict, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()){
			return "越权操作，只有超级管理员才能修改此数据！";
		}
		if (Global.isDemoMode()) {
			return "演示模式，不允许操作！";
		}

		dictService.delete(dict);
	
		return "删除成功";
	}
	
	/**
	 * 
	 * 调用批量删除的方法
	 * @param ids
	 * @param redirectAttributes
	 * @return （参数是否可空/不可空）
	 * @author vikingbin
	 * Date:2016年12月30日；
	 */
	@ResponseBody
	@RequestMapping(value = "batchDelete") 
	public String batchDelete(String ids, RedirectAttributes redirectAttributes) {
		
		if (Global.isDemoMode()) {
			return "演示模式，不允许操作！";
		}
		
		if (StringUtils.isBlank(ids)) {
			return "没有可以删除的字典id！";
		}
		
        String[]  dictIdsArr =  ids.split(",");
        List<String> dictIdList = Lists.newArrayList();
        dictIdList = Arrays.asList(dictIdsArr);
        
        dictService.batchDeleteDict(dictIdList);
	
		return "删除成功";
	}
}
